package com.mxchip.livestar.utils;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mxchip.livestar.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */

public class Utils {

    private static final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private static final String TAG = "Utils";
    private static long lastClickTime;

    /**
     * 去重复
     *
     * @param list
     * @return
     */
    public static <E> List<E> removeDuplicateWithOrder(List<E> list) {
        Set<E> set = new HashSet<>();
        List<E> newList = new ArrayList<>();
        for (E element : list) {
            if (set.add(element)) {
                newList.add(element);
            }
        }
        return newList;
    }

    /**
     * 判断字符串是否有大写字母
     *
     * @return
     */
    public static boolean isStringHasUpCase(String str) {
        boolean isUpCase = false;
        for (int i = 0; i < str.length(); i++) {
            isUpCase = Character.isUpperCase(str.charAt(i));
            if (isUpCase) break;
        }
        return isUpCase;
    }

    public static int getCharacterWidth(String text, float size) {
        if (TextUtils.isEmpty(text)) return 0;
        Paint paint = new Paint();
        paint.setTextSize(size);
        return (int) paint.measureText(text);// 得到总体长度
    }

    /**
     * 获取默认软键盘高度 单位：像素
     *
     * @return 默认软键盘高度
     */
    public static int getDefaultKeyboardHeight(@NonNull Context context) {
        return context.getResources().getDimensionPixelSize(R.dimen.default_keyboard_height);
    }

    public static void updateSoftInputMethod(Activity activity, int softInputMode) {
        if (!activity.isFinishing()) {
            WindowManager.LayoutParams params = activity.getWindow().getAttributes();
            if (params.softInputMode != softInputMode) {
                params.softInputMode = softInputMode;
                activity.getWindow().setAttributes(params);
            }
        }
    }

    /**
     * 转换dip为px
     *
     * @param context context
     * @param dip     dip
     * @return int
     */
    public static int convertDipOrPx(@NonNull Context context, float dip) {
        float scale = context.getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    public static int convertSp2Px(@NonNull Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale);
    }

    /**
     * 转换px为dip
     *
     * @param context context
     * @param px      px
     * @return float
     */
    public static float convertPxOrDip(@NonNull Context context, int px) {
        float scale = context.getApplicationContext().getResources().getDisplayMetrics().density;
        return px / scale + 0.5f * (px >= 0 ? 1 : -1);
    }

    /**
     * 获取屏幕的宽度
     *
     * @param context context
     * @return int
     */
    public static int getScreenWidth(@NonNull final Context context) {
        return context.getApplicationContext().getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight2(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen.xml");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    public static int getStatusBarHeight(@NonNull Context context) {
        int result = 0;
        int resourceId = getResources(context).getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources(context).getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 获取屏幕高度
     *
     * @param ctx context
     * @return int
     */
    public static int getScreenHeight(@NonNull Context ctx) {
        return ctx.getApplicationContext().getResources().getDisplayMetrics().heightPixels;
    }

    public static int getRealScreenWidth(Activity activity) {
        int widthPixels;
        WindowManager w = activity.getWindowManager();
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        widthPixels = metrics.widthPixels;
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
            try {
                widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
            } catch (Exception ignored) {
            }
        else if (Build.VERSION.SDK_INT >= 17)
            try {
                android.graphics.Point realSize = new android.graphics.Point();
                Display.class.getMethod("getRealSize", android.graphics.Point.class).invoke(d, realSize);
                widthPixels = realSize.x;
            } catch (Exception ignored) {
            }
        return widthPixels;
    }

    /**
     * 获取真正的屏幕高度
     *
     * @param activity
     * @return
     */
    public static int getRealScreenHeight(Activity activity) {
        int heightPixels;
        WindowManager w = activity.getWindowManager();
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        // since SDK_INT = 1;
        heightPixels = metrics.heightPixels;
        // includes window decorations (statusbar bar/navigation bar)
        if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
            try {
                heightPixels = (Integer) Display.class
                        .getMethod("getRawHeight").invoke(d);
            } catch (Exception ignored) {
            }
            // includes window decorations (statusbar bar/navigation bar)
        else if (Build.VERSION.SDK_INT >= 17)
            try {
                android.graphics.Point realSize = new android.graphics.Point();
                Display.class.getMethod("getRealSize",
                        android.graphics.Point.class).invoke(d, realSize);
                heightPixels = realSize.y;
            } catch (Exception ignored) {
            }
        return heightPixels;
    }

    /**
     * 获取状态栏高度
     *
     * @param ctx activity
     * @return int
     */
    public static int getTop(Activity ctx) {
        Rect rect = new Rect();
        ctx.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        if (rect.top == 0) {
            try {
                Class c = Class.forName("com.android.internal.R$dimen");
                Object obj = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = Integer.parseInt(field.get(obj).toString());
                return ctx.getResources().getDimensionPixelSize(x);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return rect.top;
    }

    /**
     * 获取NavigationBar的高度
     *
     * @param context
     * @return
     */
    public static int getNavigationBarHeight(Context context) {
        if (!checkDeviceHasNavigationBar(context.getApplicationContext())) {
            return 0;
        }
        Resources resources = context.getApplicationContext().getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    /**
     * 通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
     *
     * @param context
     * @return
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        return !hasMenuKey && !hasBackKey;
    }

    /**
     * 检查是否连接网络
     *
     * @param context
     * @return
     */
    public static boolean checkNetWork(Context context) {
        ConnectivityManager cwjManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        cwjManager.getActiveNetworkInfo();
        NetworkInfo networkInfo = cwjManager.getActiveNetworkInfo();
        return networkInfo != null;
    }

    /**
     * @param context if null, use the default format
     *                (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30).
     * @return
     */
    public static String getUserAgent(Context context) {
        String webUserAgent = null;
        if (context != null) {
            try {
                Class sysResCls = Class.forName("com.android.internal.R$string");
                Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
                Integer resId = (Integer) webUserAgentField.get(null);
                webUserAgent = context.getString(resId);
            } catch (Throwable ignored) {
            }
        }
        if (TextUtils.isEmpty(webUserAgent)) {
            webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
        }

        Locale locale = Locale.getDefault();
        StringBuffer buffer = new StringBuffer();
        // Add version
        final String version = Build.VERSION.RELEASE;
        if (version.length() > 0) {
            buffer.append(version);
        } else {
            // default to "1.0"
            buffer.append("1.0");
        }
        buffer.append("; ");
        final String language = locale.getLanguage();
        if (language != null) {
            buffer.append(language.toLowerCase());
            final String country = locale.getCountry();
            if (country != null) {
                buffer.append("-");
                buffer.append(country.toLowerCase());
            }
        } else {
            // default to "en"
            buffer.append("en");
        }
        // add the model for the release build
        if ("REL".equals(Build.VERSION.CODENAME)) {
            final String model = Build.MODEL;
            if (model.length() > 0) {
                buffer.append("; ");
                buffer.append(model);
            }
        }
        final String id = Build.ID;
        if (id.length() > 0) {
            buffer.append(" build/");
            buffer.append(id);
        }
        return String.format(webUserAgent, buffer, "Mobile ");
    }

    /**
     * 需要權限 READ_PHONE_STATE READ_PHONE_STATE
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        @SuppressLint("HardwareIds") String imei = mTelephonyManager.getDeviceId();
        if (TextUtils.isEmpty(imei)) {
            imei = String.valueOf(System.currentTimeMillis());
        }
        return imei;
    }

    public static String URLDecoder(String converData) {
        String json = null;
        try {
            json = URLDecoder.decode(converData, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return json;
    }

    public static String URLEncoder(String converData) {
        String json = null;
        try {
            json = URLEncoder.encode(converData, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        String versonName;
        try {
            versonName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
//            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
//            versonName = info.metaData.getString("versionName");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versonName = "1";
        }
        return versonName;
    }

    /**
     * 获取app版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode(Context context) {
        int versonName = 0;
        try {
            versonName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
//        try {
//            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
//            versonName = info.metaData.getInt("versionCode");
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//            versonName = 1;
//        }
        return versonName;
    }

    /**
     * 获取渠道名
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        String channelId = "EB_EBLOG";
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            channelId = applicationInfo.metaData.getString("UMENG_CHANNEL");
        } catch (Exception e) {

        }
        return channelId;
    }

    public final static boolean isJSONValid(String jsonInString, Class<?> clazz) {
        try {
            new Gson().fromJson(jsonInString, clazz);
            return true;
        } catch (JsonSyntaxException ex) {
            return false;
        }
    }

    public static boolean isPad(Context context) {
        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取user 信息areaCode(8位)+userId（8位）+" " +state（1位）
     *
     * @return 当前用户的Id
     */
    public static String checkUserState() {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb/config";
        if (filePath == null) return "0";

        File file = new File(filePath);
        String line = "0";
        String[] strs = new String[2];
        String number = "";

        if (file.isDirectory()) {
            Log.d(TAG, filePath + " is directory");
            return "0";
        } else {
            InputStreamReader isr = null;
            try {
                InputStream is = new FileInputStream(file);
                if (is != null) {
                    isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    line = br.readLine();
                    strs = line.split("[=]");
                    number = strs[1];
                }
            } catch (FileNotFoundException e) {
                Log.d(TAG, filePath + " doesn't found!");
            } catch (IOException e) {
                Log.d(TAG, filePath + " read exception, " + e.getMessage());
            } finally {
                try {
                    if (isr != null)
                        isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return number;
    }

    /**
     * 获取userId
     *
     * @return 当前用户的Id
     */
    public static String getUserId() {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb/config";
        if (filePath == null) return "0";

        File file = new File(filePath);
        String line = "0";
        String[] strs = new String[2];
        String number = "";

        if (file.isDirectory()) {
            Log.d(TAG, filePath + " is directory");
            return "0";
        } else {
            InputStreamReader isr = null;
            try {
                InputStream is = new FileInputStream(file);
                isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                line = br.readLine();
                strs = line.split("[=]");
                if (strs[1].length() < 8) {
                    number = strs[1];
                } else {
                    number = strs[1].split(" ")[0].substring(8);
                }
            } catch (FileNotFoundException e) {
                Log.d(TAG, filePath + " doesn't found!");
            } catch (IOException e) {
                Log.d(TAG, filePath + " read exception, " + e.getMessage());
            } finally {
                try {
                    if (isr != null)
                        isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return number;
//        Context context = Appli.getContext();
//        int userId;
//        try {
//            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
//            userId = info.metaData.getInt("userId");
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//            userId = -1;
//        }
//        return userId;
    }

    /**
     * 获取区号
     *
     * @return 当前用户的Id
     */
    public static String getAreaCode() {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb/config";
        if (filePath == null) return "0";

        File file = new File(filePath);
        String line = "0";
        String[] strs = new String[2];
        String number = "";

        if (file.isDirectory()) {
            Log.d(TAG, filePath + " is directory");
            return "0";
        } else {
            InputStreamReader isr = null;
            try {
                InputStream is = new FileInputStream(file);
                if (is != null) {
                    isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    line = br.readLine();
                    strs = line.split("[=]");
                    if (strs[1].length() < 8) {
                        number = strs[1];
                    } else {
                        number = strs[1].split(" ")[0].substring(0, 8);
                    }
                }
            } catch (FileNotFoundException e) {
                Log.d(TAG, filePath + " doesn't found!");
            } catch (IOException e) {
                Log.d(TAG, filePath + " read exception, " + e.getMessage());
            } finally {
                try {
                    if (isr != null)
                        isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return number;
    }

    /**
     * 获取区号+本机号码
     *
     * @return 当前用户的Id
     */
//    public static String getAllCode() {
//        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb/config";
//        if (filePath == null) return "0";
//
//        File file = new File(filePath);
//        String line = "0";
//        String[] strs = new String[2];
//        String number = "";
//
//        if (file.isDirectory()) {
//            Log.d(TAG, filePath + " is directory");
//            return "0";
//        } else {
//
//            InputStreamReader isr = null;
//
//            try {
//                InputStream is = new FileInputStream(file);
//                if (is != null) {
//                     isr = new InputStreamReader(is);
//                    BufferedReader br = new BufferedReader(isr);
//                    line = br.readLine();
//                    strs = line.split("[=]");
//                    if (strs[1].length() < 8) {
//                        number = strs[1];
//                    } else {
//                        number = strs[1].split(" ")[0];
//                    }
//                }
//            } catch (FileNotFoundException e) {
//                Log.d(TAG, filePath + " doesn't found!");
//            } catch (IOException e) {
//                Log.d(TAG, filePath + " read exception, " + e.getMessage());
//            }finally {
//                try {
//                    if (isr!=null)
//                    isr.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return number;
//    }
    public static void setUserId(String substring) {
        String folderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb";
        File folderFile = new File(folderPath);
        boolean mkdir = false;
        if (!folderFile.exists() || !folderFile.isDirectory()) {
            mkdir = folderFile.mkdir();
        }
        if (!mkdir) {
            mkdir = folderFile.mkdir();
        }
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hxb/config";

        File file = new File(filePath);
        if (file.isDirectory()) {
            Log.d(TAG, filePath + " is directory");
        } else {
            OutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                String userId = "userId=" + substring;
                fos.write(userId.getBytes());
            } catch (FileNotFoundException e) {
                Log.d(TAG, filePath + " doesn't found!");
            } catch (IOException e) {
                Log.d(TAG, filePath + " read exception, " + e.getMessage());
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static String getIpAddress(@NonNull Context context) {
        String ipAddress;
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            ipAddress = applicationInfo.metaData.getString("ipAddress");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            ipAddress = "124.238.237.78";
        }

        return ipAddress;
    }

    public static int getPort(@NonNull Context context) {
        int port = 0;
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            port = applicationInfo.metaData.getInt("port");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            port = 9001;
        }
        return port;
    }

    public static String getSocketAddress(Context context) {
        String socketAddress;
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            socketAddress = applicationInfo.metaData.getString("socketAddress");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            socketAddress = "47.95.123.144:33000";
        }
        return socketAddress;
    }

    /**
     * 获取数据库名字
     *
     * @param context
     * @return
     */
    public static String getDatabaseName(Context context) {
        String dbName;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            dbName = info.metaData.getString("dbName");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            dbName = "privateFundDB";
        }
        if (TextUtils.isEmpty(dbName)) {
            dbName = "privateFundDB";
        }

        return dbName;
    }

    /**
     * 数据库版本号
     *
     * @param context
     * @return
     */
    public static int getDBVersionCode(Context context) {
        int versonCode;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            versonCode = info.metaData.getInt("dbVersion");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versonCode = 1;
        }
        return versonCode;
    }

    public static boolean getIsLocal(@NonNull Context context) {
        boolean isLocal;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            isLocal = info.metaData.getBoolean("localStatus");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            isLocal = false;
        }
        return isLocal;
    }

    public static NetConfig.Env getEnv(@NonNull Context context) {
        String envStatus;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            envStatus = info.metaData.getString("localEnv");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            envStatus = "develop";
        }
        NetConfig.Env env = NetConfig.Env.develop;
        if (TextUtils.equals(envStatus, NetConfig.Env.test.name())) {
            env = NetConfig.Env.test;
        } else if (TextUtils.equals(envStatus, NetConfig.Env.stag.name())) {
            env = NetConfig.Env.stag;
        }
        return env;
    }

    public static boolean getIsOpenLeak(@NonNull Context context) {
        boolean isOpenLeak;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            isOpenLeak = info.metaData.getBoolean("openLeak");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            isOpenLeak = false;
        }
        return isOpenLeak;
    }

    /**
     * 是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    /**
     * 是否微信安装了
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager == null) return false;
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (serviceList == null || serviceList.size() == 0) return false;
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(serviceName)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 是否为中文系统
     *
     * @param context
     * @return
     */
    public static boolean isSystemZh(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return TextUtils.equals(context.getResources().getConfiguration().getLocales().get(0).getLanguage(), "zh");
        } else
            return TextUtils.equals(context.getResources().getConfiguration().locale.getLanguage(), "zh");
    }

    /**
     * 判断应用是否在前台
     *
     * @param context
     * @return
     */
    public static boolean isAppTop(final Context context) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                List<ActivityManager.AppTask> list = am.getAppTasks();
                if (list.size() > 0) {

                }
            } else {
                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                ComponentName componentInfo = taskInfo.get(0).topActivity;
                if (componentInfo.getPackageName().equals(context.getPackageName())) {
                    isTop = true;
                }
            }
        return isTop;
    }

    /**
     * 当前应用是否在后台 5.0以上不好用
     *
     * @param context
     * @return
     */
    public static boolean isAppBackground(final Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                            break;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

    /**
     * 设置华为角标
     *
     * @param context
     * @param num
     */
    public static void setHuaweiBadge(Context context, int num) {
        if (Build.MANUFACTURER.equalsIgnoreCase("huawei")) {
            try {
                Bundle bunlde = new Bundle();
                bunlde.putString("package", "com.eblog");
                bunlde.putString("class", "com.eblog.router.main.mvp.view.ui.WelcomeActivity");
                bunlde.putInt("badgenumber", num);
                context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"),
                        "change_badge", null, bunlde);
            } catch (Exception e) {
            }
        }
    }

    /**
     * 生成 固定长度的字符串
     *
     * @param str
     * @param maxNum
     * @param split
     * @return
     */
    public static String createStr(String str, int maxNum, String split) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        String[] strs = str.split(split);
        String needStartStr, needEndStr, tmpStr;
        if (strs.length > 1) {
            needEndStr = "." + strs[strs.length - 1];
            tmpStr = str.substring(0, str.length() - needEndStr.length());
        } else {
            tmpStr = str;
            needEndStr = "";
        }

        int length = tmpStr.length();
        if (length >= maxNum) {
            int startEndNum = maxNum - maxNum / 2;
            int endStartNum = length - startEndNum;
            needStartStr = tmpStr.substring(0, startEndNum) + "…" + tmpStr.substring(endStartNum, length);
        } else {
            return str;
        }

        return needStartStr + needEndStr;
    }

    public static void hideDatePickerHeader(Context context, DatePicker datePicker) {
        ViewGroup rootView = (ViewGroup) datePicker.getChildAt(0);
        if (rootView == null) {
            return;
        }
        View headerView = rootView.getChildAt(0);
        if (headerView == null) {
            return;
        }
        //5.0+
        int headerId = context.getResources().getIdentifier("day_picker_selector_layout", "id", "android");
        if (headerId == headerView.getId()) {
            headerView.setVisibility(View.GONE);

            ViewGroup.LayoutParams layoutParamsRoot = rootView.getLayoutParams();
            layoutParamsRoot.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            rootView.setLayoutParams(layoutParamsRoot);

            ViewGroup animator = (ViewGroup) rootView.getChildAt(1);
            ViewGroup.LayoutParams layoutParamsAnimator = animator.getLayoutParams();
            layoutParamsAnimator.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            animator.setLayoutParams(layoutParamsAnimator);

            View child = animator.getChildAt(0);
            ViewGroup.LayoutParams layoutParamsChild = child.getLayoutParams();
            layoutParamsChild.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            child.setLayoutParams(layoutParamsChild);
            return;
        }
        //6.0+
        headerId = context.getResources().getIdentifier("date_picker_header", "id", "android");
        if (headerId == headerView.getId()) {
            headerView.setVisibility(View.GONE);
        }
    }

    public static boolean isCameraCanUse() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            canUse = false;
        }
        if (canUse) {
            mCamera.release();
            mCamera = null;
        }
        return canUse;
    }

    /**
     * 当地时间 ---> UTC时间
     *
     * @return
     */
    public static String Local2UTC(String localTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("gmt"));
        String gmtTime = sdf.format(new Date(localTime));
        return gmtTime;
    }

    public static String Local2UTC(long localTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("gmt"));
        String gmtTime = sdf.format(new Date(localTime));
        return gmtTime;
    }

    /**
     * UTC时间 ---> 当地时间
     *
     * @param utcTime UTC时间
     * @return
     */
    public static String utc2Local(String utcTime) {
        SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//UTC时间格式
        utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date gpsUTCDate = null;
        try {
            gpsUTCDate = utcFormater.parse(utcTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当地时间格式
        localFormater.setTimeZone(TimeZone.getDefault());
        String localTime = localFormater.format(gpsUTCDate.getTime());
        return localTime;
    }

    public static void killHightProcess(@NonNull Context context) {
        ActivityManager appAM = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : appAM.getRunningAppProcesses()) {
            if (appProcess.processName.contains(":highLoad")) {
                android.os.Process.killProcess(appProcess.pid);
                break;
            }
        }
    }

    public static boolean hasHightProcess(@NonNull Context context) {
        ActivityManager appAM = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : appAM.getRunningAppProcesses()) {
            if (appProcess.processName.contains(":highLoad")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 字符统计工具类<br></>
     * 中文为2，其它为1，如需要限制汉字数据未10个，那么在比较长度时小于或等于20<br></>
     *
     * @param text
     * @return
     */
    public static int charStats(String text) {
        int length = 0;
        if (!TextUtils.isEmpty(text)) {
            String Reg = "^[\u4e00-\u9fa5]{1}$";//正则
            int result = 0;
            for (int i = 0; i < text.length(); i++) {
                String b = Character.toString(text.charAt(i));
                if (b.matches(Reg)) result++;
            }
            length = text.length() + result;
        }
        return length;
    }

    //展开或缩回动画
    public static void expandOCollapseAnim(boolean isExpand, ImageView iv) {
        expandOCollapseAnim(isExpand, iv, 300);
    }

    public static void expandOCollapseAnim(boolean isExpand, ImageView iv, int duration) {
        float start, target;
        if (isExpand) {
            start = 0f;
            target = 90f;
        } else {
            start = 90f;
            target = 0f;
        }
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(iv, View.ROTATION, start, target);
        objectAnimator.setDuration(duration);
        objectAnimator.start();
    }

    /**
     * 处理提示文本
     *
     * @param s
     * @return
     */
    public static String handlerPromptContent(String s, @NonNull Context context) {
        if (!TextUtils.isEmpty(s)) {
            if (s.contains("failed to connect to") || s.contains("502") || s.contains("404") || s.contains("failed to connect to")
                    || s.contains("No address associated with hostname"))
                s = context.getString(R.string.timeout_str);
        }
        return s;
    }

    /**
     * this screeshots form
     *
     * @param activity
     * @param isFullScreen
     */
    public static void screenshots(Activity activity, boolean isFullScreen, File mFileTemp) {
        if (mFileTemp.exists()) {
            mFileTemp.delete();
        }
        try {
            //View是你需要截图的View
            View decorView = activity.getWindow().getDecorView();
            decorView.setDrawingCacheEnabled(true);
            decorView.buildDrawingCache();
            Bitmap b1 = decorView.getDrawingCache();
            // 获取状态栏高度 /
            Rect frame = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            // 获取屏幕长和高 Get screen width and height
            int width = activity.getWindowManager().getDefaultDisplay().getWidth();
            int height = activity.getWindowManager().getDefaultDisplay().getHeight();
            // 去掉标题栏 Remove the statusBar Height
            Bitmap bitmap;
            if (isFullScreen) {
                bitmap = Bitmap.createBitmap(b1, 0, 0, width, height);
            } else {
                bitmap = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
            }
            decorView.destroyDrawingCache();
            FileOutputStream out = new FileOutputStream(mFileTemp);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getMacAddress() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig", "HWaddr");

        if (result == null) {
            return "";
        }
        if (result.length() > 0 && result.contains("HWaddr")) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            if (Mac.length() > 1) {
                result = Mac.toLowerCase();
            }
        }
        return result.trim();
    }

    private static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            //执行命令cmd，只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && line.contains(filter) == false) {
                //result += line;
                Log.i("test", "line: " + line);
            }

            result = line;
            Log.i("test", "result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean isCameraConn() {
        String result = "";
        String Mac = "";
        result = callCmd("ls /dev/", "video2");

        if (result == null) {
            return false;
        }
        return true;
    }

    /**
     * 获取状态栏高度
     */
    /*public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }*/
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

    /**
     * 获取字符串资源
     */
    public static String getString(int resId, @NonNull Context context) {
        return getResources(context).getString(resId);
    }

    /**
     * 获取Resource对象
     */
    public static Resources getResources(@NonNull Context context) {
        return context.getResources();
    }

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    public static boolean isFastClick(int second) {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= second) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }


    public static void log(String tag, String msg) {
        if (TextUtils.isEmpty(msg)) {
            msg = "";
        }
    }

    private static Map<String, Long> fastMap = new HashMap<>();

    public static boolean isFastClick(String json) {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if (fastMap.containsKey(json)) {
            Long aLong = fastMap.get(json);
            if (aLong == null) aLong = 0L;
            if ((currentClickTime - aLong) >= MIN_DELAY_TIME) {
                flag = false;
            }
            fastMap.put(json, currentClickTime);
            return flag;
        } else {
            fastMap.put(json, currentClickTime);
            return false;
        }
    }

    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]);//.append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }


    public static String stringToHex(String base) {
        StringBuffer buffer = new StringBuffer();
        int intValue;
        for (int x = 0; x < base.length(); x++) {
            int cursor = 0;
            intValue = base.charAt(x);
            String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
            for (int i = 0; i < binaryChar.length(); i++) {
                if (binaryChar.charAt(i) == '1') {
                    cursor += 1;
                }
            }
            if ((cursor % 2) > 0) {
                intValue += 128;
            }
            buffer.append(Integer.toHexString(intValue) + " ");
        }
        return buffer.toString();
    }

    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) (Integer.parseInt(subStr, 16));
        }

        return bytes;
    }


    public static Boolean isApEnabled(@NonNull Context context) {
        int state = getWifiApState(context);
        return 12 /* WIFI_AP_STATE_ENABLING*/ == state || 13 /*WIFI_AP_STATE_ENABLED*/ == state;
    }

    public static WifiManager getWifiManager(@NonNull Context context) {
        return (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    }

    public static Integer getWifiApState(Context mContext) {
        WifiManager wifiManager = getWifiManager(mContext);
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApState");
            Integer i = (Integer) method.invoke(wifiManager);
            Log.i(TAG, "wifi state:  $i");
            return i;
        } catch (Exception e) {
            Log.e(TAG, "Cannot get WiFi AP state"+e);
            return 14;/*WIFI_AP_STATE_FAILED*/
        }
    }

    // wifi热点开关
    public static Boolean setWifiApEnabled(Boolean enabled, @NonNull Context context) {
        WifiManager wifiManager = getWifiManager(context);
        if (enabled) { // disable WiFi in any case
            //wifi和热点不能同时打开，所以打开热点的时候需要关闭wifi
            ((WifiManager) (context.getSystemService(Context.WIFI_SERVICE))).setWifiEnabled(false);
        }
        try { //            //热点的配置类
            WifiConfiguration apConfig = getWifiApConfiguration(context);
            //配置热点的名称(可以在名字后面加点随机数什么的)
            String replace = Utils.getMacAddress().replace(":", "");
            String substring = replace.substring(replace.length() - 6);
            apConfig.SSID = "hxb_"+substring;
            //配置热点的密码
            apConfig.preSharedKey = "123456789";
            //通过反射调用设置热点
            Method method = WifiManager.class.getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, java.lang.Boolean.TYPE);
            //返回热点打开状态
            return ((Boolean) method.invoke(wifiManager, apConfig, enabled));
        } catch (Exception e) {
            MyLog.logE(MyLog.UTILS_MODEL,"MainActivity::setWifiApEnabled:"+e);
            return false;
        }
    }

    /**
     * 获取AP热点配置信息
     */
    private static WifiConfiguration getWifiApConfiguration(@NonNull Context context) {
        WifiManager wifiManager = getWifiManager(context);
        try {
            Method method = WifiManager.class.getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            return (WifiConfiguration) (method.invoke(wifiManager));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 判断当前网络是否为 Wifi 网络连接
     * @param context
     * @return
     */
    public static boolean isWifiConnected(@NonNull Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) return false;
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

      public static boolean isEthernet(@NonNull Context context) {
          ConnectivityManager connectMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo ethNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
          if (ethNetInfo != null && ethNetInfo.isConnected()) {
              return true;
        }
        return false;
    }


        /**
         * 获得栈中最顶层的Activity
         *
         * @param context
         * @return
         */
        public static String getTopActivity (Context context){
            android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

            if (runningTaskInfos != null) {
                return (runningTaskInfos.get(0).topActivity).toString();
            } else
                return null;
        }

        public static boolean isDebug (@NonNull Context context){
            boolean isLocal = false;
            try {
                ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                isLocal = info.metaData.getBoolean("BUGLY_ENABLE_DEBUG");
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                isLocal = false;
            }
            return isLocal;
        }

        /**
         * @param data
         * @return
         */
        public static boolean checkIsIFrame ( byte[] data){
            if (data == null || data.length < 5) {
                return false;
            }
            //data[4]为NALU类型
            if (data[0] == 0x0 && data[1] == 0x0 && data[2] == 0x0 && data[3] == 0x1 && (data[4] == 0x67 || data[4] == 0x27)) {
                return true;
            }
            byte nalu = data[4];
            if (((nalu & 0x1F) == 5)) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * @param data
         * @return 1 sps  2 pps 3 Iframe
         */
        public static int checkFrameType ( byte[] data){
            if (data == null || data.length < 5) {
                return -1;
            }
            //data[4]为NALU类型
            byte[] array = data;
            int NaluType = -1;
            if (array[0] == 0 && array[1] == 0 && array[2] == 0 && array[3] == 1) //0x00 0x00 0x00 0x01
            {
                NaluType = (array[4] & 0x1f);
            } else if (array[0] == 0 && array[1] == 0 && array[2] == 1)//0x00 0x00 0x01
            {
                NaluType = (array[3] & 0x1f);
            } else {
                return -1;
            }

            if (NaluType == 7)//SPS
            {
                return 1;
            } else if (NaluType == 8) {
                return 2;
            } else if (NaluType == 5) {
                return 3;
            }
            return -1;
        }

        public static void memcpy (Integer src, ByteBuffer buffer, Integer size){
            if (size > 4) {
                size = 4;
            }
            for (int i = 0; i < size; i++) {
                byte temp = (byte) (((src >> (3 - i)) * 8) & 0xff);
                ;
                buffer.put(temp);
            }
        }

        public static boolean isNAL ( byte[] buf, int len){
            byte[] nal3 = {0x00, 0x00, 0x01};

//        for (int i = 0; i < 3; i++) {
//           if (nal3[i] !=buf[i]&&nal3[i] !=0){
//               return false;
//           }
//
//        }

            byte[] nal4 = {0x00, 0x00, 0x00, 0x01};
            for (int i = 0; i < 4; i++) {
                if (nal4[i] != buf[i]) {
                    return false;
                }

            }


            return true;
        }

        public static boolean isSPS ( byte[] buf, int len){
            // !!! warning (buf[i] & 0x1f) == 0x07
            //if (buf[i++] == 0x00 && buf[i++] == 0x00 && buf[i++] == 0x00 && buf[i++] == 0x01 && (buf[i] & 0x1f) == 0x07) //sps
            //https://cardinalpeak.com/blog/the-h-264-sequence-parameter-set/
            //const uint8_t sps[] = { 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x0a, 0xf8, 0x41, 0xa2 };
            if (!isNAL(buf, len)) {
                return false;
            }
            return (buf[4] & 0x1f) == 0x07;
        }

        public static boolean isPPS ( byte[] buf, int len){
            // !!! warning (buf[i] & 0x1f) == 0x07
            //if (buf[i++] == 0x00 && buf[i++] == 0x00 && buf[i++] == 0x00 && buf[i++] == 0x01 && (buf[i] & 0x1f) == 0x07) //sps
            //https://cardinalpeak.com/blog/the-h-264-sequence-parameter-set/
            //const uint8_t sps[] = { 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x0a, 0xf8, 0x41, 0xa2 };
            if (!isNAL(buf, len)) {
                return false;
            }
            return (buf[4] & 0x1f) == 0x08;
        }
    }
